# coding: utf-8

# -------------------------------------------------------------------------------
# Name:         role
# Description:
# Author:       XiangjunZhao
# EMAIL:        2419352654@qq.com
# Date:         2019-11-03
# -------------------------------------------------------------------------------
from rest_framework import status
from rest_framework.mixins import UpdateModelMixin, DestroyModelMixin
from rest_framework.response import Response
from rest_framework.viewsets import ReadOnlyModelViewSet, GenericViewSet

from QAPlatform.mixins import CustomCreateModelMixin
from apps.BasicAuthService.filters import RoleFilter
from apps.BasicAuthService.models import Role
from apps.BasicAuthService.serializers import RoleSerializer, RoleListSerializer

__all__ = ['RoleListViewSet', 'RoleViewSet']


class RoleListViewSet(ReadOnlyModelViewSet):
    queryset = Role.objects.filter(is_deleted=False)
    serializer_class = RoleListSerializer
    filter_class = RoleFilter


class RoleViewSet(CustomCreateModelMixin, UpdateModelMixin, DestroyModelMixin, GenericViewSet):
    queryset = Role.objects.filter(is_deleted=False)
    serializer_class = RoleSerializer

    def destroy(self, request, *args, **kwargs):
        id = kwargs.get('pk')
        role = Role.objects.get(id=id)
        role.user.clear()
        role.permissions.clear()
        role.is_deleted = True
        role.save()
        return Response(status=status.HTTP_204_NO_CONTENT)
